import { getCurrentTimeParam } from "./globalTimeFilter.js";
import { API_CONFIG } from "./config.js";

document.addEventListener("DOMContentLoaded", function () {
  // 获取高频词统计容器
  const topBGElement = document.getElementById("bodyRightTopBG");
  if (!topBGElement) return;

  // 创建高频词统计区域
  const wordsContainer = document.createElement("div");
  wordsContainer.className = "high-frequency-words";
  wordsContainer.innerHTML = `
        <div class="words-header">
        </div>
        <div class="words-grid"></div>
    `;

  // 插入到容器中
  topBGElement.appendChild(wordsContainer);

  // 添加样式
  const style = document.createElement("style");
  style.innerHTML = `
        .high-frequency-words {
            margin: 15px 0;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid rgba(36, 187, 236, 0.2);
        }
        
        .words-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(36, 187, 236, 0.3);
        }
        
        .words-header h3 {
            font-size: 2rem;
            font-weight: 600;
            color: #24bbec;
            margin: 0;
            position: relative;
        }
        
        .words-header h3::after {
            content: '';
            position: absolute;
            bottom: -10px;
            left: 0;
            width: 60px;
            height: 3px;
            background: linear-gradient(90deg, #24bbec, transparent);
            border-radius: 3px;
        }
        
        .update-time {
            font-size: 2rem;
            color: #a2d3e8;
        }
        
        .words-grid {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            justify-content: center;
        }
        
        .word-item {
            background: rgba(10, 58, 124, 0.4);
            border-radius: 6px;
            padding: 10px 15px;
            display: flex;
            flex-direction: column;
            align-items: center;
            transition: all 0.3s ease;
            border: 1px solid rgba(36, 187, 236, 0.15);
            min-width: 100px;
        }
        
        .word-item:hover {
            transform: translateY(-5px);
            background: rgba(36, 187, 236, 0.2);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            border-color: #24bbec;
        }
        
        .word-text {
            font-size: 2rem;
            font-weight: 500;
            color: #e6f7ff;
            margin-bottom: 5px;
            text-align: center;
        }
        
        .word-count {
            font-size: 2rem;
            font-weight: bold;
            background: linear-gradient(to right, #ffc640, #ff9800);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        /* 排名靠前的词样式 */
        .word-item.top-1 {
            background: rgba(255, 198, 64, 0.2);
            border-color: #ffc640;
        }
        
        .word-item.top-1 .word-count {
            background: linear-gradient(to right, #ffc640, #ff9800);
        }
        
        .word-item.top-2 {
            background: rgba(36, 187, 236, 0.2);
            border-color: #24bbec;
        }
        
        .word-item.top-2 .word-count {
            background: linear-gradient(to right, #24bbec, #1d6fa0);
        }
        
        .word-item.top-3 {
            background: rgba(36, 211, 154, 0.2);
            border-color: #24d39a;
        }
        
        .word-item.top-3 .word-count {
            background: linear-gradient(to right, #24d39a, #1da971);
        }
    `;
  document.head.appendChild(style);

  // 初始化高频词数据
  generateHighFrequencyWords();

  // 设置定时更新（每10秒更新一次）
  setInterval(generateHighFrequencyWords, 10000000);
});

// 生成高频词数据
function generateHighFrequencyWords() {
  const id = "gfwqsddgsdhsrgsb1desswrh5tjyt";
  const type = "1";

  // 获取时间参数并格式化为YYYY-MM-DD
  const rawTime = getCurrentTimeParam();


  const params = new URLSearchParams();
  params.append("id", id);
  params.append("time", rawTime); // 使用格式化后的时间
  params.append("type", type);

  // 构建URL
  const url = `${
      API_CONFIG.BASE_URL
  }/api/metrics/${id}/single-metrics-value?${params.toString()}`;
  axios
      .get(url)
      .then((response) => {
        console.log("获取高频词数据成功:", response.data);

        const words = response.data.data;
        renderWordsGrid(words);
        updateUpdateTime();
      })
      .catch((error) => {
        console.error("获取高频词数据失败:", error);
      });
}
function formatWord(word, maxLength) {
  if (!word) return "";

  // 只取后5位字符
  let formatted = word.trim();
  if (formatted.length > maxLength) {
    formatted = formatted.substring(formatted.length - maxLength);
  }

  return formatted;
}
// 监听时间变化事件
document.addEventListener("timePeriodChanged", function () {
  generateHighFrequencyWords();
});

function renderWordsGrid(words) {
  const wordsGrid = document.querySelector(".words-grid");
  if (!wordsGrid) return;

  // 清空现有内容
  wordsGrid.innerHTML = "";

  // 只取前16个高频词
  const topWords = words.slice(0, 24);

  // 创建词块
  topWords.forEach((item, index) => {
    const wordItem = document.createElement("div");
    wordItem.className = "word-item";

    // // 为前三名添加特殊样式
    // if (index < 3) {
    //   wordItem.classList.add(`top-${index + 1}`);
    // }

    // 格式化单词显示
    const displayWord = formatWord(item.word, 5);

    wordItem.innerHTML = `
      <div class="word-text" title="${item.word}">${displayWord}</div>
      <div class="word-count">${item.word_count}</div>
    `;

    wordsGrid.appendChild(wordItem);
  });

  // 添加动画效果
  animateWords();
}
// 更新更新时间
function updateUpdateTime() {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, "0");
  const minutes = now.getMinutes().toString().padStart(2, "0");
  const seconds = now.getSeconds().toString().padStart(2, "0");

  document.getElementById(
      "words-update-time"
  ).textContent = `${hours}:${minutes}:${seconds}`;
}

// 添加动画效果
function animateWords() {
  const wordItems = document.querySelectorAll(".word-item");

  // 初始状态设置
  wordItems.forEach((item) => {
    item.style.opacity = "0";
    item.style.transform = "translateY(20px)";
  });

  // 逐个显示动画
  let delay = 0;
  wordItems.forEach((item) => {
    setTimeout(() => {
      item.style.transition = "opacity 0.5s ease, transform 0.5s ease";
      item.style.opacity = "1";
      item.style.transform = "translateY(0)";
    }, delay);

    delay += 100; // 每个词块延迟100ms显示
  });

  // 添加悬浮动画
  wordItems.forEach((item) => {
    item.addEventListener("mouseenter", function () {
      this.style.transform = "translateY(-5px)";
    });

    item.addEventListener("mouseleave", function () {
      this.style.transform = "translateY(0)";
    });
  });
}
